package com.qfjy.project.oauth;

import cn.hutool.extra.emoji.EmojiUtil;
import com.qfjy.entity.po.User;
import com.qfjy.entity.po.WeiUser;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.UserService;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Oauth 鉴权示例
 * @author yr
 * @version 1.0
 * @date 2023/11/7 20:38
 */
@RequestMapping("weixin")
@Controller
@Slf4j
public class WeiXinOauth {

    @Resource
    private WeiUserService weiUserService;
    @Resource
    private UserService userService;

    /**
     * 引导用户进入授权页面同意授权,获取code
     */
    @GetMapping("oauth")
    public void oauth(HttpServletResponse response) throws IOException {

        String redirect_url=MenuManager.REAL_URL+"/weixin/invoke";
        try {
            redirect_url = URLEncoder.encode(redirect_url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId+
                "&redirect_uri=" + redirect_url +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=java2303" +
                "#wechat_redirect";

        response.sendRedirect(url);
    }


    @GetMapping("invoke")
    public String invoke(HttpServletRequest request){
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        log.info("code-->{}",code);


        String url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + MenuManager.appId +
                "&secret=" + MenuManager.appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
        log.info("认证服务器返回资源信息:{}",jsonObject.toString());
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        String userInfoUrl="https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" + access_token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject jsonObject1 = WeixinUtil.httpRequest(userInfoUrl, "GET", null);
        request.setAttribute("r",jsonObject1);
        return "oauth";

    }


    /**
     * 个人中心 按钮 Oauth2.0授权
     */
    @GetMapping("oauthUser")
    public void oauthUser(HttpServletResponse response) throws IOException {

        String redirect_url=MenuManager.REAL_URL+"/weixin/invokeUser";
        try {
            redirect_url = URLEncoder.encode(redirect_url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId+
                "&redirect_uri=" + redirect_url +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=java2303" +
                "#wechat_redirect";

        response.sendRedirect(url);
    }

    @GetMapping("invokeUser")
    public String invokeUser(HttpServletRequest request){
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        log.info("code-->{}",code);


        String url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + MenuManager.appId +
                "&secret=" + MenuManager.appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
        log.info("认证服务器返回资源信息:{}",jsonObject.toString());
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        String userInfoUrl="https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" + access_token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject jsonObject1 = WeixinUtil.httpRequest(userInfoUrl, "GET", null);
        request.setAttribute("r",jsonObject1);
        //收集到wei_user表中
        WeiUser weiUser = weiUserService.selectWeiUserByOpenid(openid);
        if (weiUser==null){
            weiUser = new WeiUser();
            weiUser.setOpenid(jsonObject1.getString("openid"));
            weiUser.setNickname(jsonObject1.getString("nickname"));
            weiUser.setHeadimgurl(jsonObject1.getString("headimgurl"));
            weiUser.setCreateDate(new Date());

            weiUser.setNickname(EmojiUtil.removeAllEmojis(weiUser.getNickname()));

            int num = weiUserService.insertSelective(weiUser);
            log.info("收集微信个人信息成功{}",weiUser.toString());
        }else {
            log.info("微信个人信息已存在");
        }

        User user = userService.selectUserByWid(weiUser.getId());
        if (user==null){
            request.setAttribute("wid",weiUser.getId());
            request.setAttribute("openid",openid);
            return "user/login";
        }else {
            request.setAttribute("user",user);
            return "user/userInfo";
        }
    }



    /**
     * todo 会议发单 按钮 Oauth2.0授权
     */
    @GetMapping("/oauthMeetingPub")
    public void oauthMeetingPub(HttpServletResponse response) throws IOException {

        String redirect_url=MenuManager.REAL_URL+"/weixin/invokeMeetingPub";
        try {
            redirect_url = URLEncoder.encode(redirect_url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId+
                "&redirect_uri=" + redirect_url +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=java2303" +
                "#wechat_redirect";

        response.sendRedirect(url);
    }


    @GetMapping("/invokeMeetingPub")
    public String invokeMeetingPub(HttpServletRequest request){
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        log.info("code-->{}",code);


        String url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + MenuManager.appId +
                "&secret=" + MenuManager.appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
        log.info("认证服务器返回资源信息:{}",jsonObject.toString());
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        String userInfoUrl="https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" + access_token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject jsonObject1 = WeixinUtil.httpRequest(userInfoUrl, "GET", null);
        request.setAttribute("r",jsonObject1);
        //收集到wei_user表中
        WeiUser weiUser = weiUserService.selectWeiUserByOpenid(openid);
        if (weiUser==null){
            weiUser = new WeiUser();
            weiUser.setOpenid(jsonObject1.getString("openid"));
            weiUser.setNickname(jsonObject1.getString("nickname"));
            weiUser.setHeadimgurl(jsonObject1.getString("headimgurl"));
            weiUser.setCreateDate(new Date());

            weiUser.setNickname(EmojiUtil.removeAllEmojis(weiUser.getNickname()));

            int num = weiUserService.insertSelective(weiUser);
            log.info("收集微信个人信息成功{}",weiUser.toString());
        }else {
            log.info("微信个人信息已存在");
        }

        User user = userService.selectUserByWid(weiUser.getId());
        if (user==null){
            request.setAttribute("wid",weiUser.getId());
            request.setAttribute("openid",openid);
            return "user/login";
        }else {
            if (user.getRid() == 1) {
                request.setAttribute("user",user);
                // 发单组
                return "/meetingPub/meetingPubAdd";
            } else {
                // 不是发单组
                return "unauth";
            }
        }
    }


}
